/**    
 * 文件名：OpenCVImageJUtils.java    
 *    
 * 版本信息：    
 * 日期：2014年3月7日    
 * xyj 足下 xyj 2014     
 * 版权所有    
 *    
 */
package opencvtest;

import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.ImageProcessor;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.googlecode.javacv.cpp.opencv_core.IplImage;

/**
 * @项目名称：opencv-test
 * @类名称：OpenCVImageJUtils
 * @类描述：
 * @创建人：zhuyi
 * @创建时间：2014年3月7日 下午5:32:43
 * @修改人：zhuyi
 * @修改时间：2014年3月7日 下午5:32:43
 * @修改备注：
 * @version
 * 
 */
public class OpenCVImageJUtils {

    /**
     * Convert OpenCV `IplImage` to ImageJ's ImageProcessor.
     * 
     * Depending on the type input image different instance of `ImageProcessor`
     * will be created, for color images it will be `ColorProcessor`, for 8-bit
     * gray level `ByteProcessor`. Other pixel types are currently not
     * supported.
     * 
     * @param image
     *            input image.
     */
    public static ImageProcessor toImageProcessor(IplImage image) {
        BufferedImage bi = image.getBufferedImage();
        ImageProcessor ip = null;
        switch (bi.getType()) {
        case BufferedImage.TYPE_BYTE_GRAY:
            ip = new ByteProcessor(bi);
            break;
        case BufferedImage.TYPE_3BYTE_BGR:
            ip = new ColorProcessor(bi);
            break;
        default:
            throw new IllegalArgumentException("Unsupported BufferedImage type " + bi.getType());
        }
        return ip;
    }

    /**
     * Convert OpenCV `IplImage` to ImageJ's `ColorProcessor`.
     * 
     * @param image
     *            input image.
     * @throws IllegalArgumentException
     *             if `IplImage` is not a color image.
     */
    public static ColorProcessor toColorProcessor(IplImage image) {
        ImageProcessor ip = toImageProcessor(image);
        if (ip instanceof ColorProcessor) {
            return (ColorProcessor) ip;
        } else {
            throw new IllegalArgumentException("Input image is not a color image.");
        }
    }

    public static BufferedImage toBufferedImage(ImageProcessor ip) {
        if (ip instanceof ByteProcessor) {
            return ip.getBufferedImage();
        } else if (ip instanceof ColorProcessor) {
            BufferedImage dest = new BufferedImage(ip.getWidth(), ip.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
            Graphics g = dest.getGraphics();
            g.drawImage(ip.getBufferedImage(), 0, 0, null);
            return dest;
        } else {
            throw new IllegalArgumentException("Unsupported ImageProcessor type:  " + ip.getClass());
        }
    }

}
